<template>
  <div>
    <a-collapse class="!mt-4" v-model="activeKey">
      <a-collapse-panel key="1" header="发起单据">
       <KFormBuild class="k-form-design" ref="kfbStart" :dynamicData="dynamicDataSatrt" disabled  :value="formModel" />
      </a-collapse-panel>
      <a-collapse-panel key="2" header="待办单据" v-if="task.hasForm">
        <TaskForm class="k-form-design" ref="kfbPend" :task="task" :formData="formData" :id="id" />
      </a-collapse-panel>
    </a-collapse>
  </div>
</template>

<script>
import { getAction } from '@/services/manage'
import { KFormBuild } from '@/components/k-form-design/packages/use.js'
import { getSelectDictCode, getSelectOptions } from '@/utils/k-form-design'
import { mapMutations } from 'vuex'
import TaskForm from './modules/TaskForm'
import { ACCESS_TOKEN, ACCESS_REFRESH_TOKEN } from '@/store/mutation-types'
import Criteria from '@/utils/criteria'
import { OPERATOR } from '@/store/mutation-types'
export default {
  name: 'bpmnForm',
  components: { KFormBuild, TaskForm },
  mixins: [],
  props: {
    type: String // handling:办理 || claim:拾取 || history:审核历史
  },
  data() {
    return {
      url: {
        flowDef: '/camunda/process/details/',
        complete: '/camunda/task/complete/', // 审核通过
        rejectlast: '/camunda/task/reject/last/', // 退回上一节点
        rejectfirst: '/camunda/task/reject/first/', // 退回发起人
        claim: '/camunda/task/claim/', // 拾取
        historics: '/camunda/task/historics/', // 审批流程数据
        active: '/camunda/task/active/',
        task: '/camunda/task/all/page'// 当前节点任务详情
      },
      formModel: { }, // 表单设计model
      formDef: {}, // 表单设计信息
      flowDef: {}, // 流程设计信息
      formData: {}, // 表单数据信息
      dynamicDataSatrt: {},
      processInstanceId: '',
      isInit: '',
      activeKey: ['1', '2'],
      task: {},
      bpmnType: '',
      platform: '' // 平台环境
    }
  },
  methods: {
    ...mapMutations('account', ['setToken', 'setRefreshToken']),
    async getflowForm(task) { // 根据流程定义id获取绑定表单-发起单据及流程
      try {
        this.confirmLoading = true
        const res = await getAction(this.url.flowDef + this.processInstanceId)
        if (!res.success) {
          this.confirmLoading = false
          return this.$message.warning('未查询到发起表单')
        }
        const formModel = res.result.startFormModelDef && res.result.startFormModelDef.model && JSON.parse(res.result.startFormModelDef.model)

        // 必须在渲染前获取到dynamicData --start
        let dictCodes = getSelectDictCode(formModel.list)
        dictCodes = Array.from(new Set(dictCodes))
        this.dynamicDataSatrt = await getSelectOptions(dictCodes)
        // -- end
        // formModel.list = replaceFormModel(formModel.list)

        this.formModel = formModel
        this.flowDef = res.result
        this.formDef = res.result.formModelDef
        this.formData = res.result.startDatas

        this.$nextTick(() => {
          const startDatas = res.result.startDatas
          Object.keys(startDatas).forEach(key => {
            this.isJsonString(startDatas[key]) ? startDatas[key] = JSON.parse(startDatas[key]) : ''
          })
          this.$refs.kfbStart.setData(startDatas)
        })
        this.confirmLoading = false
      } catch (error) {
        this.confirmLoading = false
      }
    },
    async getTask() { // 获取当前节点任务详情
      const params = this.getQueryParams()
      const res = await getAction(this.url.task, params)
      if (res.success) {
        this.task = res.result.content[0]
      }
    },
    getQueryParams() { // 获取查询条件
      const queryParam = new Criteria()
      queryParam.addCriterions({ id: this.id }, OPERATOR.EQ)// 过滤参数转换为jpa支持格式
      var param = Object.assign({}, { criteria: queryParam.getEncode() })
      return param
    },
    isJsonString(str) {
      try {
        const toObj = JSON.parse(str) // json字符串转对象
        /*
          判断条件
          1. 排除null可能性
          2. 确保数据是对象或数组
        */
        if (toObj && typeof toObj === 'object') {
          return true
        }
      } catch {
        // console.error('err')
        return false
      }
      return false
    },
    updateBpmnStatus(state) {
      this.$refs.kfbStart.updateBpmnStatus && this.$refs.kfbStart.updateBpmnStatus({ task: {
        processInstanceId: this.processInstanceId,
        id: this.id
      }, formData: this.formData, state })
    },
    getData() {
      console.log('获取待办数据' + this.task.hasForm)
      if (this.task.hasForm && this.$refs.kfbPend) { // 当前节点有节点表单
        console.log('获取待办数据1')
        this.$refs.kfbPend.getData().then(values => {
          console.log('获取待办数据3' + window.uni)
          window.uni.postMessage({
            data: {
              type: 'completed',
              data: values
            }
          })
        }).catch(() => {
          this.confirmLoading = false
          console.log('验证未通过，获取失败')
        })
      } else { // 当前节点无节点表单
        console.log('获取待办数据2')
        window.uni.postMessage({
          data: {
            type: 'completed',
            data: {}
          }
        })
      }
    },
    updateToken({ token, refreshToken }) {
      this.setToken(token)
      this.setRefreshToken(refreshToken)
      if (this.bpmnType === 'handling') {
        this.getTask()
      }
      this.getflowForm()
    }
  },
  async created() {
    const { processInstanceId, id, bpmnType, platform } = this.$route.query
    this.processInstanceId = processInstanceId
    this.id = id
    this.bpmnType = bpmnType
    this.platform = platform
    window.updateBpmnStatus = (data) => {
      this.updateBpmnStatus(data.state)
    }
    window.updateToken = (data) => {
      this.updateToken(data)
    }
    window.getData = (data) => {
      this.getData(data)
    }
    const that = this
    if (platform === 'app') {
      // Android环境
      document.addEventListener('UniAppJSBridgeReady', function() {
        window.uni.getEnv((res) => {
          console.log('当前环境：' + JSON.stringify(res))
          if (res.plus) {
            if (this.isInit) {
              return
            }
            this.isInit = true
            that.updateToken({
              token: window.plus.storage.getItem(ACCESS_TOKEN),
              refreshToken: window.plus.storage.getItem(ACCESS_REFRESH_TOKEN)
            })
          }
        })
      })
    } else if (platform === 'web') { // H5
      window.addEventListener('message', function(event) {
        console.log(event)
        if (event.data.type === 'callFunction') {
          that[event.data.functionName](JSON.parse(event.data.data)) // 调用内部函数
        }
      })
    }
    // const that = this
  },
  mounted() {
    if (this.platform === 'app') {
      setTimeout(() => {
        if (!this.isInit) {
          console.log('初始化', window)
          this.isInit = true
          this.updateToken({
            token: window.plus.storage.getItem(ACCESS_TOKEN),
            refreshToken: window.plus.storage.getItem(ACCESS_REFRESH_TOKEN)
          })
        }
      }, 3000)
    }
  }
}
</script>
